package com.csw.android.dev_utils.ex

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.csw.android.dev_utils.ex.ActivityEx.bindVM

object FragmentEx {

    /**
     * 绑定ViewModel
     */
    inline fun <reified V : ViewModel> Fragment.bindVM(): V {
        return ViewModelProvider(this).get(V::class.java)
    }

    /**
     * 绑定Activity上的ViewModel
     */
    inline fun <reified V : ViewModel> Fragment.bindActivityVM(): V {
        return requireActivity().bindVM()
    }

    /**
     * 确保参数对象不为空
     */
    fun Fragment.ensureArguments(): Bundle {
        return arguments ?: Bundle()
    }

    /**
     * 获取AppCompatActivity，若所依附的activity不是AppCompatActivity，则返回空
     */
    fun Fragment.getAppCompatActivity(): AppCompatActivity? {
        val a = activity
        if (a is AppCompatActivity) {
            return a
        }
        return null
    }
}